package com.javase.多线程.线程间共享数据;

/**
 * @Auther: liyanhao
 * @Description: 线程间共享数据
 * @Date: 2022/5/18 01:33
 * @Version: v1.0
 */
public class ThreadData {
    private int j = 0;
    public synchronized void add(){
        j++;
        System.out.println(Thread.currentThread().getName()+"j 为："+j);
    }
    public synchronized void desc(){
        j--;
        System.out.println(Thread.currentThread().getName()+"j 为："+j);
    }
}

class AddRunable implements Runnable {
    ThreadData threadData;

    public AddRunable(ThreadData threadData) {
        this.threadData = threadData;
    }

    @Override
    public void run() {
        threadData.add();
    }
}
class DecRunnable implements Runnable{
    ThreadData threadData;

    public DecRunnable(ThreadData threadData) {
        this.threadData = threadData;
    }

    @Override
    public void run() {
        threadData.desc();
    }
}
class Main{
    public static void main(String[] args) {
        ThreadData threadData = new ThreadData();
        AddRunable addRunable = new AddRunable(threadData);
        DecRunnable decRunnable = new DecRunnable(threadData);
        for (int i = 0; i < 2; i++) {
            new Thread(addRunable).start();
            new Thread(decRunnable).start();
        }
    }
}
